package com.rttmall.shopbackend.app.gambling.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.PageHelper;
import com.rttmall.shopbackend.app.gambling.mapper.GamblingPeriodCustomMapper;
import com.rttmall.shopbackend.app.gambling.mapper.GamblingPeriodMapper;
import com.rttmall.shopbackend.app.gambling.mapper.ProductCustomMapper;
import com.rttmall.shopbackend.app.gambling.mapper.ProductMapper;
import com.rttmall.shopbackend.app.gambling.pojo.Category;
import com.rttmall.shopbackend.app.gambling.pojo.GamblingPeriod;
import com.rttmall.shopbackend.app.gambling.pojo.Product;
import com.rttmall.shopbackend.app.gambling.pojo.ProductCustom;
import com.rttmall.shopbackend.app.gambling.service.ProductService;
import com.rttmall.shopbackend.app.service.OssService;
import com.rttmall.shopbackend.app.service.UploadImageService;
import com.rttmall.shopbackend.enums.PeriodShippingStatus;
import com.rttmall.shopbackend.enums.PeriodStatus;
import com.rttmall.shopbackend.enums.ProductStatus;
import com.rttmall.shopbackend.exception.ServiceException;
import com.rttmall.shopbackend.pojo.PageBean;
import com.rttmall.shopbackend.pojo.Pagination;
import com.rttmall.shopbackend.utils.Constants;
@SuppressWarnings("all")
@Service
public class ProductServiceImpl implements ProductService {
	@Value("${product.imgPath}")
    private String imgPath;
	
	public static final int FIRST_PERIOD = 1;

	@Autowired
	private ProductCustomMapper productCustomMapper;
	@Autowired
	private ProductMapper productMapper;
	@Autowired
	private GamblingPeriodMapper gamblingPeriodMapper;
	@Autowired
	private GamblingPeriodCustomMapper gamblingPeriodCustomMapper;
	@Autowired
	private UploadImageService uploadImageService;
    @Autowired
    private OssService ossService;
	@Override
	public Map queryProduct(ProductCustom productCustom) {
		Map map = new HashMap();
        List<ProductCustom> productCustomList = productCustomMapper.queryProduct(productCustom);
        productCustomList.forEach(w->{
            w.setImage("<img style='width:50px;height:50px;' src='"+imgPath+w.getImage()+"' alt='商品'/>");
        });
        int sum = productCustomMapper.queryProductCount(productCustom);
        map.put("data", productCustomList);
        map.put("total", sum);
        return map;
	}
	@Override
	public Map queryVirtualProduct(String keyText, Pagination grid) {
		Map map = new HashMap();
		PageHelper.startPage(grid.getPageIndex()+1, grid.getPageSize());
		List<Product> productList = productCustomMapper.queryVirtualProduct(keyText);
		PageBean<Product> pb = new PageBean(productList);
        map.put("data", productList);
        map.put("total", pb.getTotal());
        return map;
	}
	/**
	 * 添加商品
	 */
	@Override
	public void addProductSubmit(MultipartHttpServletRequest multiRequest,
			Product product) throws Exception {
		List<String> list = new ArrayList<>();
		try {
			uploadImageService.productUploadImg(multiRequest,product);
			list.add(product.getImage());
			productCustomMapper.insertSelective(product);
			if(product.getStatus()==ProductStatus.SHELVES.ordinal()){
				addPeriod(product,FIRST_PERIOD);
				throw new RuntimeException();
			}
		} catch (Exception e) {
			ossService.deleteObjectList(list);
			throw new ServiceException(Constants.UPDATE_ERROR);
		}
		
	}
	/**
	 * 更新查询商品信息
	 */
	@Override
	public Product editQueryProduct(Integer id) {
		Product product = productMapper.selectByPrimaryKey(id);
		if (null != product) {
			if (!StringUtils.isEmpty(product.getImage())) {
				product.setImage(imgPath + product.getImage());
			}
		}
		return product;
	}
	/**
	 * 更新商品
	 */
	@Override
	public void updateProductSubmit(MultipartHttpServletRequest multiRequest,
			Product product) throws Exception {
		uploadImageService.productUploadImg(multiRequest,product);
		productMapper.updateByPrimaryKeySelective(product);
		if(product.getStatus()==ProductStatus.SHELVES.ordinal()){
			//查询该商品最新期号
			GamblingPeriod gamblingPeriod = gamblingPeriodCustomMapper.queryProductMaxPeriod(product.getId());
			//添加期数信息,先判断目前有没有进行中的期数
			if(null == gamblingPeriod){
				addPeriod(product,FIRST_PERIOD);
			}else if(gamblingPeriod.getStatus()==PeriodStatus.OVER.ordinal()){
				addPeriod(product,gamblingPeriod.getPeriod()+1);
			}
		}
		
	}
	/**
	 * 添加期数信息
	 * @param product
	 */
	public void addPeriod(Product product,int period){
		GamblingPeriod gamblingPeriod = new GamblingPeriod();
		gamblingPeriod.setCreateTime(new Date().getTime());
		gamblingPeriod.setCountryCode(product.getCountryCode());
		gamblingPeriod.setPeriod(period);
		gamblingPeriod.setProductId(product.getId());
		gamblingPeriod.setRemainingCount(product.getSellingPrice());
		gamblingPeriod.setTotalCount(product.getSellingPrice());
		gamblingPeriod.setShippingStatus(PeriodShippingStatus.NOT_RECEIVED_GOODS.ordinal());
		gamblingPeriod.setStatus(PeriodStatus.NOW.ordinal());
		gamblingPeriodMapper.insertSelective(gamblingPeriod);
	}
	/**
	 * 批量上架、下架
	 */
	@Override
	public void batchEditProductStatus(List<String> productIdList, Integer flag)
			throws Exception {
		List<Integer> list = productIdList.stream().map(w->Integer.parseInt(w.trim())).collect(Collectors.toList());
		int status ;
		//先确保状态一致（查询这些商品）
		List<ProductCustom> productCustomList = productCustomMapper.batchQueryProductAndMaxPeriod(list);
		long count = productCustomList.stream().map(w->w.getStatus()).distinct().count();
		if(count!=1){
			throw new ServiceException(Constants.STATUS_ATYPISM);
		}
		//批量更新商品状态
		productCustomMapper.batchEditProductStatus(list,flag);
		if(flag==ProductStatus.SHELVES.ordinal() && productCustomList.get(0).getStatus()==ProductStatus.NOTSHELVES.ordinal()){
			//批量添加期数信息,先判断目前有没有进行中的期数
			List<ProductCustom> result = productCustomList.stream().filter(w->w.getGamblingPeriod().getStatus()==PeriodStatus.OVER.ordinal()).collect(Collectors.toList());
			List<GamblingPeriod> GamblingPeriodList = new ArrayList<>();
			result.forEach(s->{
				GamblingPeriod gamblingPeriod = new GamblingPeriod();
				gamblingPeriod.setCreateTime(new Date().getTime());
				gamblingPeriod.setCountryCode(s.getCountryCode());
				gamblingPeriod.setPeriod(s.getGamblingPeriod().getPeriod()+1);
				gamblingPeriod.setProductId(s.getId());
				gamblingPeriod.setRemainingCount(s.getSellingPrice());
				gamblingPeriod.setTotalCount(s.getSellingPrice());
				gamblingPeriod.setShippingStatus(PeriodShippingStatus.NOT_RECEIVED_GOODS.ordinal());
				gamblingPeriod.setStatus(PeriodStatus.NOW.ordinal());
				GamblingPeriodList.add(gamblingPeriod);
			});
			if(GamblingPeriodList.size()>0){
				gamblingPeriodCustomMapper.batchInsertPeriod(GamblingPeriodList);
			}
		}
	}
	@Override
	public List<Category> findAllCategory() {
		return productCustomMapper.findAllCategory();
	}
}
